import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Account } from '../entities/account.entity';
import { AuthService } from '../auth/auth.service';
import { Injectable } from '@nestjs/common';
@Injectable()
export class MailAccountService {
  constructor(
    @InjectRepository(Account)
    private accountRepository: Repository<Account>,
    private authService: AuthService,
  ) {}
  async create(account: Account, req: any) {
    account.user_id = req.user.id;
    if (!account.remark) {
      account.remark = account.email_account;
    }
    const newAccount = this.accountRepository.create(account);
    try {
      await this.accountRepository.save(newAccount);
      return { code: 200, data: { id: newAccount.id } };
    } catch (e) {
      return { code: 500, message: e.message };
    }
  }
  findAll() {
    return this.accountRepository.find();
  }
  findOne(id: string) {
    return this.accountRepository.findOne({ where: { id: parseInt(id) } });
  }
  async update(id: string, account: Account) {
    await this.accountRepository.update(id, account);
    return this.accountRepository.findOne({ where: { id: parseInt(id) } });
  }
  async remove(id: string) {
    // TODO: 校验这个账号配置是否属于该用户

    try {
      await this.accountRepository.delete(id);
      return { code: 200, message: '已删除' };
    } catch (e) {
      return { code: 500, message: e.message };
    }
  }
}
